import React , {Component} from 'react';
import propTypes from 'prop-types';

// 函数式组件
function FormatterDate (props) {
    return <div>现在是 { props.date.toLocaleTimeString() }</div>
}
//类式组件
class Navigator extends Component {
    //构造器是否接受props,是否传递props,取决于：是否希望在构造器中通过this访问props
    constructor (props) {
        super(props);
        // console.log('constructor',this); //this --> 当前的实例对象 Navigator
        // console.log(this.props);
        this.state = {
            date: new Date()
        }
    }

    // 对标签属性进行类型、 必要性的限制
    static propTypes = {
        name: propTypes.string.isRequired, //限制name必传,且为字符串
        age: propTypes.number,
        sex: propTypes.string,
        speak: propTypes.func //限制speak为函数
    }

    // 指定默认标签属性值
    static defaultProps = {
        age: 18,
        sex: '男'
    }

    componentDidMount () {
        this.props.speak();
        this.timer = setInterval(() => {
            this.tick()
        },1000);
    }
    componentWillUnmount () {
        clearInterval(this.timer);
    }
    tick () {
        this.setState({
            date: new Date()
        })
    }
    
    render () {
        // console.log(this); //this --> 当前的实例对象 Navigator
        const { name, age, sex } = this.props;
        return (
            <div>
                <FormatterDate date={ new Date() } />
                <ul>
                    <li>{name}</li>
                    <li>{age + 2}</li>
                    <li>{sex}</li>
                </ul>
            </div>
        )
    }
}
export default Navigator;